import React, { useContext, useEffect, useState } from 'react';
import { createBrowserHistory } from 'history';

const RouterContext = React.createContext();

export const BrowserRouter = (props) => {
    const history = createBrowserHistory();

    const [location, setLocation] = useState(history.location);

    useEffect(() => {
        let unlistener = history.listen(({ location }) => {
            setLocation(location);
        });
        return () => {
            if (unlistener) {
                unlistener();
            }
        };
    }, [history]);

    return (
        <RouterContext.Provider value={{ history, location }}>
            {props.children}
        </RouterContext.Provider>
    );
};

export const Route = ({ path }) => {
    location.pathname === path;
    return 123;
};

export const Link = ({ to, children }) => {
    const { history } = useContext(RouterContext);

    const handleClick = (e) => {
        e.preventDefault();
        history.push(to);
    };

    return (
        <a href={to} onClick={handleClick}>
            {children}
        </a>
    );
};
